const { app, BrowserWindow, ipcMain, Menu, globalShortcut } = require('electron')
const path = require('path')

let currentAppCode = null

function createWindow () {
  const win = new BrowserWindow({
    width: 1280,
    height: 640,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })

  // 注册F11快捷键
  globalShortcut.register('F11', () => {
    const win = BrowserWindow.getFocusedWindow()
    if (win) {
      win.webContents.toggleDevTools()
    }
  })

  // 创建菜单
  const template = [
    {
      label: '操作',
      submenu: [
        {
          label: '重新登录',
          click: () => {
            const win = BrowserWindow.getFocusedWindow()
            if (win) {
              win.loadFile('index.html')
            }
          }
        },
        {
          label: '刷新页面',
          click: () => {
            const win = BrowserWindow.getFocusedWindow()
            if (win && currentAppCode) {
              win.webContents.reload()
            }
          }
        },
        { type: 'separator' },
        {
          label: '开发者工具',
          accelerator: 'F11',
          click: () => {
            const win = BrowserWindow.getFocusedWindow()
            if (win) {
              win.webContents.toggleDevTools()
            }
          }
        }
      ]
    }
  ]
  
  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)

  win.loadFile('index.html')
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 处理导航请求
ipcMain.on('navigate', (event, { url, appCode }) => {
  const win = BrowserWindow.getFocusedWindow()
  if (win) {
    currentAppCode = appCode
    win.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
      details.requestHeaders['X-Apig-AppCode'] = appCode
      callback({ requestHeaders: details.requestHeaders })
    })
    win.loadURL(url)
  }
}) 